import cv2
import random

image = cv2.imread("images/image.jpg")

# Rotate and change scale
r, c = image.shape[: 2]
M = cv2.getRotationMatrix2D((c/2, r/2), 45, 0.6)
image2 = cv2.warpAffine(image, M, (c, r))

gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray_img2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)

# SIFT
sift_obj = cv2.SIFT_create()
kp, desc = sift_obj.detectAndCompute(gray_img, None)
kp2, desc2 = sift_obj.detectAndCompute(gray_img2, None)

# Use BFMatcher to match
bfm = cv2.BFMatcher()
matches = bfm.knnMatch(desc, desc2, k=2)

# Apply ratio test, get good matches
good = []
for m, n in matches:
    if m.distance < 0.4 * n.distance:
        good.append([m])

# Shuffle the matched keypoints
random.shuffle(good)

image_match = cv2.drawMatchesKnn(image, kp, image2, kp2, good[: 10], None, flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)

cv2.imwrite("images/sift_matches.jpg", image_match)
